package quq.missq.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import com.android.volley.VolleyError;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.PhotoAlbumAdapter;
import quq.missq.beans.Attach;
import quq.missq.beans.PhotoBean;
import quq.missq.utils.HttpRequest;
import quq.missq.utils.ImageUploadAsyncTask;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;

/**
 * Created by River on 8/13/15.
 */
public class PhotoInAlbumActivity extends BaseActivity implements VolleyTool.HTTPListener,
        SwipeRefreshLayout.OnRefreshListener,View.OnClickListener{

    private RecyclerView mRecyclerView;
    private StaggeredGridLayoutManager mStaggeredGridLayoutManager;
    private PhotoAlbumAdapter adapter;
    private View mFootView;
    private LinkedList<Attach> results;
    private ImageView mBack;
    private ImageView mAdd;
    private ProgressDialog dialog;

    private int maxResults = 10;
    private int currentPage = 1;
    private int id = -1;
    private int type = -1;
    private boolean isLoadingMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_in_album_activity);
        currentPage = 1;
        id = getIntent().getExtras().getInt("id");
        type = getIntent().getExtras().getInt("type");
        initView();
        initData();
        initListener();
        loadNetworkData();
    }

    private void initView(){
        mBack = (ImageView)findViewById(R.id.back);
        mAdd = (ImageView)findViewById(R.id.add);
        if(type == 5){
            mAdd.setVisibility(View.GONE);
        }
        mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        mStaggeredGridLayoutManager =  new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        //******************************
//        SpacesItemDecoration spacesItemDecoration = new SpacesItemDecoration(6);
//        mRecyclerView.addItemDecoration(spacesItemDecoration);
        //******************************
        mRecyclerView.setLayoutManager(mStaggeredGridLayoutManager);
    }
    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpacesItemDecoration(int space) {
            this.space=space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left=space;
            outRect.right=space;
            outRect.bottom=space;
            if(parent.getChildAdapterPosition(view)==0){
                outRect.top=space;
            }
        }
    }
    private void initData(){
        results = new LinkedList<>();
        adapter = new PhotoAlbumAdapter(this);
        adapter.setData(results);
        mRecyclerView.setAdapter(adapter);
    }

    private void loadNetworkData(){
        Map<String,String> params = new HashMap<>();
        params.put("id", id+"");
        params.put("pn",currentPage+"");
        params.put("maxResults",maxResults+"");
        VolleyTool.get(this,Constants.PHOTOES_IN_ALBUM_URL, params, this, Constants.PHOTOES_IN_ALBUM, PhotoBean.class);
    }

    private void initListener(){
        mBack.setOnClickListener(this);
        mAdd.setOnClickListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int[] visibleItems = mStaggeredGridLayoutManager.findLastVisibleItemPositions(null);
                int lastitem = Math.max(visibleItems[0],visibleItems[1]);
                if (dy > 0 && lastitem == adapter.getItemCount()-1 && !isLoadingMore) {
                    isLoadingMore = true;
                    currentPage = currentPage+1;
                    loadNetworkData();
                    operateFootView(true);
                }
            }
        });
    }

    private void operateFootView(boolean isDisplay){
        if(mFootView == null){
            mFootView = mRecyclerView.findViewWithTag("footView");
        }
        if(isDisplay){
            mFootView.setVisibility(View.VISIBLE);
        }else {
            mFootView.setVisibility(View.GONE);
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        PhotoBean bsBean = (PhotoBean)t;
        if(bsBean.getCode() >= 0){
            LinkedList<Attach> beans = bsBean.getData().getResults();
            if(currentPage == 1){
                adapter.getData().clear();
                adapter.getData().addAll(0, beans);
                adapter.notifyDataSetChanged();
            }else{
                if(beans.size() > 0){
                    int startPosition = adapter.getItemCount();
                    adapter.getData().addAll(beans);
                    adapter.notifyItemRangeInserted(startPosition,beans.size());
                }else{
                    if(results.size() > 10){
                        showToast("已加载完所有");
                    }
                }
                operateFootView(false);
            }
        }else{
            showToast(bsBean.getMessage());
        }
        isLoadingMore = false;
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        loadNetworkData();
    }

    private static final int CHOOSE_PIC = 0;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.add:
                Intent intent = new Intent(this, PhotoSelectorActivity.class);
                intent.putExtra(PhotoSelectorActivity.KEY_MAX, 9);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent, CHOOSE_PIC);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == CHOOSE_PIC) {
            ArrayList<PhotoModel> photos = (ArrayList<PhotoModel>) data.getSerializableExtra("photos");
            dialog = ProgressDialog.show(this, "提示", "上传中...", false, false);
            Map<String,File> files = new HashMap<>();
            File file;
            for (int i=0;i<photos.size();i++){
                file = new File(photos.get(i).getOriginalPath());
                files.put("pic"+i,file);
            }
            Map<String,String> params = new HashMap<>();
            params.put("albumId",id+"");
            params.put("acc_token", UserTools.getUser(this).getAcc_token());
            ImageUploadAsyncTask imageUploadAsyncTask = new ImageUploadAsyncTask(params,files, Constants.ADD_PHOTO_TO_ALBUM_URL,new HttpRequest.HttpRequestListener() {
                @Override
                public void httpError() {
                    if(dialog!=null){dialog.dismiss();}
                    showToast("发布失败，请重试");
                }

                @Override
                public void httpSuccess(String msg) {
                    MLog.e(msg);
                    if(dialog!=null){dialog.dismiss();}
                    try {
                        JSONObject obj = new JSONObject(msg);
                        int code = obj.getInt("code");
                        String message = obj.getString("message");
                        if(code >= 0){
                            onRefresh();
                        }else{
                            showToast(message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },"files");
            imageUploadAsyncTask.execute();
        }
    }
}
